<template>
  <Dialog v-model="dialogVisible" title="添加已有用户" maxHeight="300px">
    <!--<Search
      :model="{ title: '' }"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />
    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    />-->
    <ContentWrap>
      <div class="search-box">
        <el-input v-model="objParams.username" clearable />
        <el-button type="primary" @click="getuserList('')">
            <el-icon style="vertical-align: middle">
                <Search />
            </el-icon>
            <span style="vertical-align: middle">查询</span>
        </el-button>
        <el-button type="primary" @click="setSearchParams()">
            <el-icon style="vertical-align: middle"><RefreshRight /></el-icon>
            <span style="vertical-align: middle">重置</span>
        </el-button>
      </div>
      <div class="choose-box">
        <p>
          已选择 角色名称：
          <template v-for="item of multipleSelection"
            ><i style="margin-right: 5px">{{ item.realname }}</i>
          </template>
          <span v-if="multipleSelection.length != 0" @click="onEmpty"> 清空 </span>
        </p>
      </div>
      <div class="table-box">
        <el-table
          ref="multipleTableRef"
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >

            <!--          @select="handleSelectionChange"-->
            <!--          @select-all="handleSelectionChangeAll"-->
            <!--        >-->
          <el-table-column type="selection" width="55" />
          <el-table-column property="username" label="用户账号" show-overflow-tooltip />
          <el-table-column property="realname" label="用户名称" show-overflow-tooltip />
          <el-table-column property="createTime" label="性别" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="scope.row.sex == 1">男</span>
              <span v-else-if="scope.row.sex == 2">女</span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column property="phone" label="电话" show-overflow-tooltip />
          <el-table-column property="orgCodeTxt" label="部门" show-overflow-tooltip />
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :current-page="objParams.pageNo"
          :page-size="objParams.pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :small="false"
          :disabled="false"
          :background="false"
          layout="total, sizes, prev, pager, next"
          :total="objParams.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 10px; display: flex; justify-content: center"
        />
      </div>
    </ContentWrap>
    <template #footer>
      <ElButton type="primary" :loading="loading" @click="save">
        {{ t('RoleManage.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('RoleManage.close') }}</ElButton>
    </template>
  </Dialog>
</template>
<script setup lang="ts" name="UserDialog">
import { ref, reactive, nextTick } from 'vue'
import {ElButton, ElMessage, ElTable} from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { getUserListApi, delTableListApi } from '@/api/table/role'
import { userListApi } from '@/api/userManage/index'
import { Dialog } from '@/components/Dialog'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { postAddUserRole } from '@/api/roleManage'
import {RefreshRight} from "@element-plus/icons-vue";
import {indexOf} from "lodash-es";
const dialogVisible = ref(false)
const roleId = ref('')
const loading = ref(false)

const { t } = useI18n()
// const dialogProps = ref({})

// const { register, tableObject, methods } = useTable<TableData>({
//   getListApi: getUserListApi,
//   delListApi: delTableListApi,
//   response: {
//     list: 'result',
//     total: 'total'
//   },
//   defaultParams: { roleParams: '1' }
// })
// const { getList, setSearchParams } = methods
// getList()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'username',
    label: t('RoleManage.username'),
    search: {
      show: true
    }
  },
  {
    field: 'realname',
    label: t('RoleManage.realname')
  },
  {
    field: 'sex_dictText',
    label: t('RoleManage.sex_dictText')
  },
  {
    field: 'phone',
    label: t('RoleManage.phone')
  },
  {
    field: 'orgCode',
    label: t('RoleManage.orgCode')
  }
])
// 重置
const setSearchParams = () => {
    objParams.username = ''
    getuserList('')
}
const getroleUserList = ref({})
const { allSchemas } = useCrudSchemas(crudSchemas)
// 接收父组件传过来的参数
const acceptParams = (params) => {
  //   dialogProps.value = params
  dialogVisible.value = params.type
  roleId.value = params.roleId
  getroleUserList.value = params.func
  multipleSelection.value = []
  getuserList('')
}
defineExpose({
  acceptParams
})
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref([])
const showMultipleSelection = ref([])
const objParams: any = reactive({
  pageNo: 1,
  pageSize: 10,
  username: '',
  total: 0
})
const tableData: any = ref([])
// 获取角色列表
const getuserList = async (params) => {
  params ? (objParams.roleName = params) : ''
  const res = await userListApi(objParams).finally(() => {
    loading.value = false
  })
  if (res) {
    tableData.value = res.result?.records
    objParams.total = res.result?.total
      nextTick(()=>{
          let data = [];
          for(let s of multipleSelection.value){
              for(let t of tableData.value){
                  if(s.id === t.id){
                      data.push(t)
                  }
              }
          }
          toggleSelection(data)
      })
      // if(multipleSelection.value.length!=0){
      //     toggleSelection(multipleSelection.value)
      // }
  }
}
// 显示已选账号
const handleSelectionChange = (val: any) => {
    showMultipleSelection.value = val
    if(multipleSelection.value.length != 0){
        for (let i = 0; i<multipleSelection.value.length; i++){
            for (let item of tableData.value) {
                if(multipleSelection.value[i].id == item.id){
                    multipleSelection.value.splice(i,1)
                }
            }
        }
    }
    let arr = multipleSelection.value
    if(val.length != 0 && val.length == tableData.value.length){
        for (let item of val) {
            if(arr.length != 0){
                for (let itemTwo =0; itemTwo < arr.length; itemTwo++) {
                    if(item.id != arr[itemTwo].id){
                        multipleSelection.value.push(item)
                        break
                    }
                }
            }else {
                multipleSelection.value.push(item)
            }
        }
    } else if(val.length != 0 && val.length < tableData.value.length){
        for(let item of tableData.value){
            for(let i =0; i < arr.length; i++){
                if (arr[i].id == item.id) {
                    arr.splice(i,1)
                    break
                }
            }
        }
        for (let valitem of val) {
            arr.push(valitem)
        }
        multipleSelection.value = arr
    } else {
        if(multipleSelection.value.length != 0){
            for (let i = 0; i<multipleSelection.value.length; i++){
                for (let item of tableData.value) {
                    if(multipleSelection.value[i].id == item.id){
                        multipleSelection.value.splice(i,1)
                    }
                }
            }
        }
    }
}
const toggleSelection = (rows) => {
    if (rows) {
        rows.forEach((row) => {
            // TODO: improvement typing when refactor table
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-expect-error
            multipleTableRef.value!.toggleRowSelection(row, undefined)
        })
    } else {
        multipleTableRef.value!.clearSelection()
    }
}
// 全选
const handleSelectionChangeAll = (data) => {
    debugger
    if(data.length > 0){
        let multipleArr = [] // 所有去重后的ID
        let multipleArrID = [] // 所有的选中ID
        let multipleArrAllArr = [] // 所有去重后的数据
        for(let item of data){
            multipleArrID.push(item.id)
        }
        for(let item of multipleSelection.value){
            multipleArrID.push(item.id)
        }
        if(multipleArrID.length !=0 ) {
            for (let i = 0; i < multipleArrID.length; i++) {
                if (multipleArr.indexOf(multipleArrID[i]) === -1) {
                    multipleArr.push(multipleArrID[i])
                }
            }
        }
        if(multipleArr.length != 0){
            for(let item of multipleArr){
                if (multipleSelection.value.length == 0){
                    multipleSelection.value = data
                    return
                }else {
                    for(let itemarr of multipleSelection.value){
                        if (itemarr.id == item) {
                            multipleArrAllArr.push(itemarr)
                        }
                    }
                }
            }
        }
        multipleSelection.value = multipleArrAllArr
    }else {
        if(multipleSelection.value.length !=0 ) {
            for (let i = 0; i < multipleSelection.value.length; i++) {
                for(let item of tableData.value){
                    if (multipleSelection.value[i].id == item.id) {
                        multipleSelection.value.splice(i,1)
                    }
                }
                i--
            }
        }
        debugger
    }
}

// 清空已选
const onEmpty = () => {
  multipleSelection.value = []
  multipleTableRef.value!.clearSelection()
}
// 分页
const handleSizeChange = (val: number) => {
  objParams.pageSize = val
  getuserList('')
}
const handleCurrentChange = (val: number) => {
  objParams.pageNo = val
  getuserList('')
}
const emit = defineEmits(['getUserRoleList'])
//
const save = async () => {
  loading.value = true
  let userIdList = []
  for (let item of multipleSelection.value) {
    userIdList.push(item.id)
  }
  let params = {
    roleId: roleId.value,
    userIdList: userIdList
  }
  const res = await postAddUserRole(params)
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (res) {
    ElMessage({
        type: res.code == 200 ? 'success' : 'warning',
        message: res.message
    })
    dialogVisible.value = false
    // tableObject.currentPage = 1
    emit('getUserRoleList', 1);
  }
}
</script>
<style scoped lang="less">
@import '../index.less';
</style>
